package com.numbfish.utils;

import org.junit.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Underscore2CamelCase {
    @Test
    public void test1() {
        String originalString = "select     u.id,u.user_name ,u.user_password  ,u.user_email,u.user_info,u.head_img,u.create_time from sys_user u;";
        System.out.println(replace(originalString));

    }

    // 将语句分为两部分
    public String replace(String sql) {
        sql=sql.replaceAll("\\s+"," ");
        System.out.println(sql);
        // 按指定模式在字符串查找
        String pattern = ".*(select)(.*)(from.*)";


        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        Matcher m = r.matcher(sql);
        if (m.find()) {
            return m.group(1)+translate2CamelCase(m.group(2))+m.group(3);
        }
        return "";
    }

    /**
     *
     * @param sql sql查询字段
     * @return  替换后的字段
     */
    public String translate2CamelCase(String sql) {
        Pattern pattern = Pattern.compile("([a-z]*)_([a-z]*)");
        Matcher matcher = pattern.matcher(sql);

        // 用于构建新字符串的 StringBuffer
        StringBuffer sb = new StringBuffer();

        // 用于追踪替换过程
        while (matcher.find()) {
            // 替换匹配到的部分为 "slow"
            // 第一次匹配到的是quick 第二次撇配到的是lazy
            String left = matcher.group(1);
            String right = matcher.group(2);
            right = right.substring(0, 1).toUpperCase() + right.substring(1);
            // System.out.println("left: "+left);
            // System.out.println("right: "+right);
            //System.out.println(matcher.group(0));
            matcher.appendReplacement(sb, matcher.group(0)+" as "+left+right);
        }
        // 将剩余部分追加到 StringBuffer
        matcher.appendTail(sb);

        // 输出最终的字符串
        //System.out.println(sb.toString()); // 输出: The slow brown fox jumps over the slow dog.
        return sb.toString();
    }


}
